﻿using Mogubang_Sl.Core;
using Mogubang_Sl.Entity;
using Mogubang_Sl.Pages;
using Mogubang_Sl.Utils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Threading;

namespace Mogubang_Sl.Views
{
    public class GameCanvas : Canvas
    {
        /// <summary>
        /// 0-没有道具准备使用 1-使用木头 2-使用炸弹
        /// </summary>
        public int ToolUseStatus { get; set; }

        MoguData[,] datas = new MoguData[GameStatics.RowColumnCount, GameStatics.RowColumnCount];
        MoguItem[,] moguItems = new MoguItem[GameStatics.RowColumnCount, GameStatics.RowColumnCount];

        int emptyRow = -1, emptyColumn = -1;
        int lastEmptyRow = -1, lastEmptyColumn = -1;
        int currDirection = -1;
        int selectRow = -1, selectColumn = -1;
        List<int> findItems = new List<int>();
        bool isManipulationStarted = false;
        object isDoingJobSyncObj = new object();
        bool isDoingJob = false;
        int currentCombo = 0;
        AddToolItem toolItem = new AddToolItem();

        Random r = new Random(DateTime.Now.Millisecond);

        /// <summary>
        /// ctor
        /// </summary>
        public GameCanvas()
        {
            ToolUseStatus = 0;
            this.ManipulationStarted += gameCanvas_ManipulationStarted;
            this.ManipulationDelta += gameCanvas_ManipulationDelta;
            this.ManipulationCompleted += gameCanvas_ManipulationCompleted;
            this.Tap += GameCanvas_Tap;

            CompositeTransform ct = new CompositeTransform();
            ct.CenterX = .5;
            ct.CenterY = .5;
            toolItem.RenderTransform = ct;
            Canvas.SetLeft(toolItem, 240 - toolItem.Width / 2);
            Canvas.SetTop(toolItem, 240 - toolItem.Height / 2);
            Canvas.SetZIndex(toolItem, 100);
        }

        void GameCanvas_Tap(object sender, GestureEventArgs e)
        {
            if (ToolUseStatus == 1)
            {
                #region 使用木头道具

                //Wood
                Point point = e.GetPosition(this);
                int clickRow = (int)point.Y / GameStatics.ItemSize;
                int clickColumn = (int)point.X / GameStatics.ItemSize;

                //判断点击的是哪个
                bool isMatch = false;
                if (woodToolItems.Count > 0)
                {
                    foreach (var lst in woodToolItems)
                    {
                        int cIndex = GetIndex(clickRow, clickColumn);
                        if (lst.Contains(cIndex))
                        {
                            //提示用户需要20个金币才能够使用
                            if (MessageBox.Show("Use WOOD need " + GameStatics.ToolPriceWood + " Gold，Determine to use ?", "Use tool", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                            {
                                if (StageManager.Instance.TotalG >= GameStatics.ToolPriceWood)
                                {
                                    StageManager.Instance.TotalG -= GameStatics.ToolPriceWood;

                                    //找到
                                    isMatch = true;

                                    //音效
                                    SoundManager.PlayEffect(SoundManager.usewood);

                                    //上锁
                                    lock (isDoingJobSyncObj)
                                    {
                                        if (isDoingJob)
                                        {
                                            return;
                                        }
                                        isDoingJob = true;
                                    }

                                    MoguType type = datas[clickRow, clickColumn].Type;
                                    int level = datas[clickRow, clickColumn].Level;

                                    List<LocationChangeInfo> changeInfoList = new List<LocationChangeInfo>();

                                    //合成目标
                                    int aimRow = lst[0] / GameStatics.RowColumnCount;
                                    int aimColumn = lst[0] % GameStatics.RowColumnCount;

                                    //找到一个，进行消除和合并
                                    foreach (var findIndex in lst)
                                    {
                                        int itemRow = findIndex / GameStatics.RowColumnCount;
                                        int itemColumn = findIndex % GameStatics.RowColumnCount;

                                        changeInfoList.Add(new LocationChangeInfo()
                                        {
                                            FromColumn = itemColumn,
                                            FromRow = itemRow,
                                            ToColumn = aimColumn,
                                            ToRow = aimRow
                                        });
                                        if (moguItems[itemRow, itemColumn] != null)
                                        {
                                            moguItems[itemRow, itemColumn].Hide();
                                        }
                                    }

                                    //减少游戏生命
                                    GamePage.Instance.SubGameLife();

                                    //减掉道具数量
                                    StageManager.Instance.WoodCount--;
                                    GamePage.Instance.UpdateStatusUI();

                                    double delay = 300;
                                    bool isCanContinueHebin = MoguLogicHelper.IsCanContinueHebin(type, level);


                                    if (isCanContinueHebin)
                                    {
                                        delay = ExchangeItem(changeInfoList);
                                    }

                                    //音效
                                    if (type == MoguType.BlueMogu)
                                    {
                                        SoundManager.PlayEffect(SoundManager.ele_diamond);
                                    }
                                    else if (type == MoguType.ET)
                                    {
                                        SoundManager.PlayEffect(SoundManager.ele_et);
                                    }
                                    else if (type == MoguType.OrangeMogu)
                                    {
                                        SoundManager.PlayEffect(SoundManager.ele_wood);
                                    }

                                    DispatcherTimer afterEliminateTimer = new DispatcherTimer();
                                    afterEliminateTimer.Interval = TimeSpan.FromMilliseconds(delay);
                                    afterEliminateTimer.Tick += (object ss, EventArgs ee) =>
                                    {
                                        //停止Timer
                                        afterEliminateTimer.Stop();

                                        //待紧缩的列
                                        List<int> columns = new List<int>();

                                        foreach (var item in changeInfoList)
                                        {
                                            if (!columns.Contains(item.FromColumn))
                                            {
                                                columns.Add(item.FromColumn);
                                            }
                                            //消除
                                            if (moguItems[item.FromRow, item.FromColumn] != null)
                                            {
                                                this.Children.Remove(moguItems[item.FromRow, item.FromColumn]);
                                                moguItems[item.FromRow, item.FromColumn] = null;
                                            }
                                            datas[item.FromRow, item.FromColumn].Type = MoguType.Null;
                                        }

                                        if (isCanContinueHebin)
                                        {
                                            //新增一个合并后的项目
                                            if (datas[aimRow, aimColumn].Type == MoguType.Null)
                                            {
                                                datas[aimRow, aimColumn].Type = type;
                                                datas[aimRow, aimColumn].Level = level + 1;
                                                moguItems[aimRow, aimColumn] = new MoguItem();
                                                moguItems[aimRow, aimColumn].SetMoguUI(datas[aimRow, aimColumn]);
                                                Canvas.SetTop(moguItems[aimRow, aimColumn], aimRow * GameStatics.ItemSize);
                                                Canvas.SetLeft(moguItems[aimRow, aimColumn], aimColumn * GameStatics.ItemSize);
                                                moguItems[aimRow, aimColumn].grid.Opacity = 0;
                                                this.Children.Add(moguItems[aimRow, aimColumn]);
                                                moguItems[aimRow, aimColumn].Show();
                                                lastEmptyColumn = -1;
                                                lastEmptyRow = -1;
                                            }
                                        }
                                        else
                                        {
                                            if (type == MoguType.OrangeMogu)
                                            {
                                                //木头
                                                AddWoodTool(aimRow, aimColumn);
                                            }
                                            else if (type == MoguType.ET)
                                            {
                                                AddBombTool(aimRow, aimColumn);
                                            }
                                        }

                                        //消除完毕，落下item，填补新item
                                        foreach (int column in columns)
                                        {
                                            MoveBottom(column);
                                        }
                                        //新增moguItem
                                        AddNewMoguItem();

                                        TurnNextLockDirection();
                                    };
                                    afterEliminateTimer.Start();
                                }
                                else
                                {
                                    //提示金币不足
                                    MessageBox.Show("Sorry, you have not enough gold.");
                                }
                            }
                        }
                    }
                }
                if (isMatch)
                {
                    UseWood();
                }

                #endregion
            }
            else if (ToolUseStatus == 2)
            {
                #region 使用炸弹

                //Bomb
                Point point = e.GetPosition(this);
                int clickRow = (int)point.Y / GameStatics.ItemSize;
                int clickColumn = (int)point.X / GameStatics.ItemSize;

                if (datas[clickRow, clickColumn].Type != MoguType.Null
                    && datas[clickRow, clickColumn].Type != MoguType.Empty)
                {
                    if (MessageBox.Show("Use BOMB need " + GameStatics.ToolPriceBomb + " Gold，Determine to use ?", "Use tool", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                    {
                        if (StageManager.Instance.TotalG >= GameStatics.ToolPriceBomb)
                        {
                            StageManager.Instance.TotalG -= GameStatics.ToolPriceBomb;

                            lock (isDoingJobSyncObj)
                            {
                                if (isDoingJob)
                                {
                                    return;
                                }
                                isDoingJob = true;
                            }

                            //消除该元素
                            //TODO lc 此处需要有炸弹效果

                            //减少游戏生命
                            GamePage.Instance.SubGameLife();

                            //减掉道具数量
                            StageManager.Instance.BombCount--;
                            GamePage.Instance.UpdateStatusUI();

                            moguItems[clickRow, clickColumn].Hide();

                            //音效
                            SoundManager.PlayEffect(SoundManager.usebomb);

                            DispatcherTimer bombTimer = new DispatcherTimer();
                            bombTimer.Interval = TimeSpan.FromMilliseconds(300);
                            bombTimer.Tick += (object ss, EventArgs ee) =>
                            {
                                bombTimer.Stop();

                                //清空数据
                                //消除
                                if (moguItems[clickRow, clickColumn] != null)
                                {
                                    this.Children.Remove(moguItems[clickRow, clickColumn]);
                                    moguItems[clickRow, clickColumn] = null;
                                }
                                datas[clickRow, clickColumn].Type = MoguType.Null;

                                //下落
                                MoveBottom(clickColumn);
                                //新增
                                AddNewMoguItem();

                                TurnNextLockDirection();
                            };
                            bombTimer.Start();

                            UseBomb();
                        }
                        else
                        {
                            //提示金币不足
                            MessageBox.Show("Sorry, you have not enough gold.");
                            UseBomb();
                        }
                    }
                }

                #endregion
            }
        }

        void gameCanvas_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
        {
            //滑动结束

            if (ToolUseStatus != 0 || GamePage.Instance.currLife <= 0)
            {
                //如果正在使用道具，则不响应，直接返回
                isManipulationStarted = false;
                selectRow = -1;
                selectColumn = -1;
                return;
            }
            if (isManipulationStarted)
            {
                lock (isDoingJobSyncObj)
                {
                    if (isDoingJob)
                    {
                        isManipulationStarted = false;
                        return;
                    }
                    isDoingJob = true;
                }

                //重置Combo
                currentCombo = 0;

                if (selectRow >= 0 && selectRow < GameStatics.RowColumnCount && selectColumn >= 0 && selectColumn < GameStatics.RowColumnCount)
                {
                    //获取滑动方向 0-Left 1-Right 2-Top 3-Bottom
                    int direction = GetDirection(e.TotalManipulation.Translation);
                    if (direction >= 0)
                    {
                        bool isMoved = false;
                        currDirection = direction;
                        //根据初始位置开始进行移动
                        switch (direction)
                        {
                            case 0:
                                //向左
                                isMoved = MoveLeft(selectRow, selectColumn);
                                break;
                            case 1:
                                //向右
                                isMoved = MoveRight(selectRow, selectColumn);
                                break;
                            case 2:
                                //向上
                                isMoved = MoveTop(selectRow, selectColumn);
                                break;
                            case 3:
                                //向下
                                isMoved = MoveBottom(selectRow, selectColumn);
                                break;
                        }

                        if (!isMoved)
                        {
                            //清空目前行列中可能移动过的项的rendertransform
                            ClearTransform();
                            //音效
                            SoundManager.PlayEffect(SoundManager.cannotmove);
                            lock (isDoingJobSyncObj)
                            {
                                isDoingJob = false;
                            }
                        }
                        else
                        {
                            //减少游戏生命
                            GamePage.Instance.SubGameLife();

                            TurnNextLockDirection();
                        }
                    }
                    else
                    {
                        //清空目前行列中可能移动过的项的rendertransform
                        ClearTransform();
                        lock (isDoingJobSyncObj)
                        {
                            isDoingJob = false;
                        }
                    }

                }

                isManipulationStarted = false;
            }
            selectRow = -1;
            selectColumn = -1;
        }

        private void ClearTransform()
        {
            for (int i = 0; i < GameStatics.RowColumnCount; i++)
            {
                if (moguItems[selectRow, i] != null)
                {
                    CompositeTransform tr2 = moguItems[selectRow, i].RenderTransform as CompositeTransform;
                    tr2.TranslateX = 0;
                    tr2.TranslateY = 0;
                }
                if (moguItems[i, selectColumn] != null)
                {
                    CompositeTransform tr2 = moguItems[i, selectColumn].RenderTransform as CompositeTransform;
                    tr2.TranslateX = 0;
                    tr2.TranslateY = 0;
                }
            }
        }

        void gameCanvas_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
        {
            if (isManipulationStarted && !isDoingJob && ToolUseStatus == 0)
            {
                if (selectRow >= 0 && selectRow < GameStatics.RowColumnCount && selectColumn >= 0 && selectColumn < GameStatics.RowColumnCount)
                {
                    int direction = GetDirectionInMoving(e.CumulativeManipulation.Translation);

                    if (direction >= 0)
                    {
                        if (MoguLogicHelper.CanMove(datas, direction, selectRow, selectColumn, emptyRow, emptyColumn))
                        {
                            //针对需要移动的想设置位移
                            if (direction == 0)
                            {
                                //向左
                                if (emptyRow == selectRow && emptyColumn < selectColumn)
                                {
                                    //可以移动
                                    double moveUnit = e.CumulativeManipulation.Translation.X;
                                    if (moveUnit < -80)
                                    {
                                        moveUnit = -80;
                                    }
                                    for (int i = emptyColumn + 1; i <= selectColumn; i++)
                                    {
                                        //找到交换位置，数据交换
                                        //设置位移值
                                        CompositeTransform tr = moguItems[selectRow, i].RenderTransform as CompositeTransform;
                                        tr.TranslateX = moveUnit;
                                    }
                                }
                            }
                            else if (direction == 1)
                            {
                                //向右
                                if (emptyRow == selectRow && emptyColumn > selectColumn)
                                {
                                    //可以移动
                                    double moveUnit = e.CumulativeManipulation.Translation.X;
                                    if (moveUnit > 80)
                                    {
                                        moveUnit = 80;
                                    }
                                    for (int i = selectColumn; i <= emptyColumn - 1; i++)
                                    {
                                        //找到交换位置，数据交换
                                        //设置位移值
                                        CompositeTransform tr = moguItems[selectRow, i].RenderTransform as CompositeTransform;
                                        tr.TranslateX = moveUnit;
                                    }
                                }
                            }
                            if (direction == 2)
                            {
                                //向上
                                if (emptyRow < selectRow && emptyColumn == selectColumn)
                                {
                                    //可以移动
                                    double moveUnit = e.CumulativeManipulation.Translation.Y;
                                    if (moveUnit < -80)
                                    {
                                        moveUnit = -80;
                                    }
                                    for (int i = emptyRow + 1; i <= selectRow; i++)
                                    {
                                        //找到交换位置，数据交换
                                        //设置位移值
                                        CompositeTransform tr = moguItems[i, selectColumn].RenderTransform as CompositeTransform;
                                        tr.TranslateY = moveUnit;
                                    }
                                }
                            }
                            else if (direction == 3)
                            {
                                //向右
                                if (emptyRow > selectRow && emptyColumn == selectColumn)
                                {
                                    //可以移动
                                    double moveUnit = e.CumulativeManipulation.Translation.Y;
                                    if (moveUnit > 80)
                                    {
                                        moveUnit = 80;
                                    }
                                    for (int i = selectRow; i <= emptyRow - 1; i++)
                                    {
                                        //找到交换位置，数据交换
                                        //设置位移值
                                        CompositeTransform tr = moguItems[i, selectColumn].RenderTransform as CompositeTransform;
                                        tr.TranslateY = moveUnit;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        void gameCanvas_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
            //开始滑动
            if (!isManipulationStarted)
            {
                isManipulationStarted = true;
                selectColumn = (int)e.ManipulationOrigin.X / GameStatics.ItemSize;
                selectRow = (int)e.ManipulationOrigin.Y / GameStatics.ItemSize;
            }
        }

        public void ContinueGame()
        {
            datas = MoguDataHelper.DictionaryToMoguData(StageManager.Instance.LastStage.moguDatas);

            //加载UI
            this.Children.Clear();
            this.Children.Add(toolItem);
            for (int i = 0; i < GameStatics.RowColumnCount; i++)
            {
                for (int j = 0; j < GameStatics.RowColumnCount; j++)
                {
                    if (datas[i, j].Type != MoguType.Empty)
                    {
                        MoguItem item = new MoguItem();
                        item.SetMoguUI(datas[i, j]);
                        Canvas.SetLeft(item, j * GameStatics.ItemSize);
                        Canvas.SetTop(item, i * GameStatics.ItemSize);
                        this.Children.Add(item);
                        moguItems[i, j] = item;
                    }
                    else
                    {
                        emptyRow = i;
                        emptyColumn = j;
                    }
                }
            }

            //设置锁定的UI
            UpdateLockUI();
        }

        public void StartNew()
        {
            emptyRow = r.Next(GameStatics.RowColumnCount);
            emptyColumn = r.Next(GameStatics.RowColumnCount);

            for (int i = 0; i < GameStatics.RowColumnCount; i++)
            {
                for (int j = 0; j < GameStatics.RowColumnCount; j++)
                {
                    datas[i, j] = new MoguData();
                    datas[i, j].Level = -1;
                    datas[i, j].Type = MoguType.Empty;
                }
            }

            //加载UI
            this.Children.Clear();
            this.Children.Add(toolItem);
            for (int i = 0; i < GameStatics.RowColumnCount; i++)
            {
                for (int j = 0; j < GameStatics.RowColumnCount; j++)
                {
                    //首次生成数据不能生成ET
                    datas[i, j].Type = MoguLogicHelper.GenMoguType(false);
                    datas[i, j].Level = MoguLogicHelper.GenLevel(datas[i, j].Type);

                    if (i == emptyRow && j == emptyColumn)
                    {
                        datas[i, j].Type = MoguType.Empty;
                        datas[i, j].Level = -1;
                        continue;
                    }
                    else
                    {

                        while (true)
                        {
                            findItems.Clear();
                            findItems.Add(i * GameStatics.RowColumnCount + j);
                            FindRelationGameItem(datas[i, j].Type, datas[i, j].Level, i, j, FindType.All, findItems);
                            if (findItems.Count > 2)
                            {
                                //生成数据
                                datas[i, j].Type = MoguLogicHelper.GenMoguType(false);
                                datas[i, j].Level = MoguLogicHelper.GenLevel(datas[i, j].Type);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }

                    MoguItem item = new MoguItem();
                    item.SetMoguUI(datas[i, j]);
                    Canvas.SetLeft(item, j * GameStatics.ItemSize);
                    Canvas.SetTop(item, i * GameStatics.ItemSize);
                    this.Children.Add(item);
                    moguItems[i, j] = item;
                }
            }
        }

        /// <summary>
        /// 轮播锁定方向
        /// </summary>
        private void TurnNextLockDirection()
        {
            for (int i = 0; i < GameStatics.RowColumnCount; i++)
            {
                for (int j = 0; j < GameStatics.RowColumnCount; j++)
                {
                    if (datas[i, j].Type == MoguType.ET && datas[i, j].Level == 1)
                    {
                        datas[i, j].TurnETSide();
                    }
                }
            }
            UpdateLockUI();
        }

        /// <summary>
        /// 更改锁定UI
        /// </summary>
        private void UpdateLockUI()
        {
            for (int i = 0; i < GameStatics.RowColumnCount; i++)
            {
                for (int j = 0; j < GameStatics.RowColumnCount; j++)
                {
                    if (moguItems[i, j] != null)
                    {
                        moguItems[i, j].SetUnBubble();
                    }
                }
            }

            for (int i = 0; i < GameStatics.RowColumnCount; i++)
            {
                for (int j = 0; j < GameStatics.RowColumnCount; j++)
                {
                    MoguData tempData = datas[i, j];
                    if (tempData.Type == MoguType.ET && tempData.Level == 1)
                    {
                        //需要去锁定别的Item
                        if (tempData.ET_Side == 2)
                        {
                            if (i > 0)
                            {
                                if (datas[i - 1, j] != null && datas[i - 1, j].Type != MoguType.ET)
                                {
                                    //锁定
                                    if (moguItems[i - 1, j] != null)
                                    {
                                        moguItems[i - 1, j].SetBubble(3);
                                    }
                                }
                            }
                        }
                        else if (tempData.ET_Side == 3)
                        {
                            if (i < GameStatics.RowColumnCount - 1)
                            {
                                if (datas[i + 1, j] != null && datas[i + 1, j].Type != MoguType.ET)
                                {
                                    //锁定
                                    if (moguItems[i + 1, j] != null)
                                    {
                                        moguItems[i + 1, j].SetBubble(2);
                                    }
                                }
                            }
                        }
                        else if (tempData.ET_Side == 0)
                        {
                            if (j > 0)
                            {
                                if (datas[i, j - 1] != null && datas[i, j - 1].Type != MoguType.ET)
                                {
                                    //锁定
                                    if (moguItems[i, j - 1] != null)
                                    {
                                        moguItems[i, j - 1].SetBubble(1);
                                    }
                                }
                            }
                        }
                        else if (tempData.ET_Side == 1)
                        {
                            if (j < GameStatics.RowColumnCount - 1)
                            {
                                if (datas[i, j + 1] != null && datas[i, j + 1].Type != MoguType.ET)
                                {
                                    //锁定
                                    if (moguItems[i, j + 1] != null)
                                    {
                                        moguItems[i, j + 1].SetBubble(0);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }


        /// <summary>
        /// 交换数据并做交换动画
        /// </summary>
        /// <param name="changeInfoList"></param>
        private void ExchangeData(List<LocationChangeInfo> changeInfoList)
        {
            //进行重排动画
            //double delay = ExchangeItem(changeInfoList);
            double delay = 200;

            //进行模块重排
            foreach (var lcItem in changeInfoList)
            {
                //重新排列数据
                MoguData temp = datas[lcItem.FromRow, lcItem.FromColumn];
                datas[lcItem.FromRow, lcItem.FromColumn] = datas[lcItem.ToRow, lcItem.ToColumn];
                datas[lcItem.ToRow, lcItem.ToColumn] = temp;

                MoguItem tempItem = moguItems[lcItem.FromRow, lcItem.FromColumn];
                moguItems[lcItem.FromRow, lcItem.FromColumn] = moguItems[lcItem.ToRow, lcItem.ToColumn];
                moguItems[lcItem.ToRow, lcItem.ToColumn] = tempItem;

                //取消位移,设定位置
                if (moguItems[lcItem.FromRow, lcItem.FromColumn] != null)
                {
                    CompositeTransform tr1 = moguItems[lcItem.FromRow, lcItem.FromColumn].RenderTransform as CompositeTransform;
                    tr1.TranslateX = 0;
                    tr1.TranslateY = 0;
                    Canvas.SetLeft(moguItems[lcItem.FromRow, lcItem.FromColumn], lcItem.FromColumn * GameStatics.ItemSize);
                    Canvas.SetTop(moguItems[lcItem.FromRow, lcItem.FromColumn], lcItem.FromRow * GameStatics.ItemSize);
                }
                if (moguItems[lcItem.ToRow, lcItem.ToColumn] != null)
                {
                    CompositeTransform tr2 = moguItems[lcItem.ToRow, lcItem.ToColumn].RenderTransform as CompositeTransform;
                    tr2.TranslateX = 0;
                    tr2.TranslateY = 0;
                    Canvas.SetLeft(moguItems[lcItem.ToRow, lcItem.ToColumn], lcItem.ToColumn * GameStatics.ItemSize);
                    Canvas.SetTop(moguItems[lcItem.ToRow, lcItem.ToColumn], lcItem.ToRow * GameStatics.ItemSize);
                }


            }

            DispatcherTimer delayTimer = new DispatcherTimer();
            delayTimer.Interval = TimeSpan.FromMilliseconds(delay + 100);
            delayTimer.Tick += (object sender, EventArgs e) =>
            {
                //处理消除逻辑
                CheckEliminate();
                delayTimer.Stop();
            };
            delayTimer.Start();
        }

        /// <summary>
        /// 检查消除
        /// </summary>
        private void CheckEliminate()
        {
            List<int> findItems = new List<int>();
            bool isFound = false;
            MoguType type = 0;
            int moguLevel = 0;
            for (int i = 0; i < GameStatics.RowColumnCount; i++)
            {
                for (int j = 0; j < GameStatics.RowColumnCount; j++)
                {
                    if (datas[i, j].Type == MoguType.Null || datas[i, j].Type == MoguType.Empty)
                    {
                        continue;
                    }

                    findItems.Clear();
                    findItems.Add(i * GameStatics.RowColumnCount + j);
                    FindRelationGameItem(datas[i, j].Type, datas[i, j].Level, i, j, FindType.All, findItems);
                    if (findItems.Count > 2)
                    {
                        isFound = true;
                        type = datas[i, j].Type;
                        moguLevel = datas[i, j].Level;
                        break;
                    }
                }
                if (isFound)
                {
                    break;
                }
            }

            double delay = 300;

            if (isFound)
            {
                List<LocationChangeInfo> changeInfoList = new List<LocationChangeInfo>();

                int aimRow = 0;
                int aimColumn = 0;

                aimRow = findItems[0] / GameStatics.RowColumnCount;
                aimColumn = findItems[0] % GameStatics.RowColumnCount;

                //确定合并目标
                foreach (var findIndex in findItems)
                {
                    int itemRow = findIndex / GameStatics.RowColumnCount;
                    int itemColumn = findIndex % GameStatics.RowColumnCount;


                    if (itemRow == lastEmptyRow && itemColumn == lastEmptyColumn)
                    {
                        aimRow = itemRow;
                        aimColumn = itemColumn;
                        break;
                    }
                    else
                    {
                        if (currDirection == 0 || currDirection == 1)
                        {
                            if (itemRow == lastEmptyRow)
                            {
                                aimRow = itemRow;
                                aimColumn = itemColumn;
                            }
                        }
                        else if (currDirection == 2 || currDirection == 3)
                        {
                            if (itemColumn == lastEmptyColumn)
                            {
                                aimRow = itemRow;
                                aimColumn = itemColumn;
                            }
                        }
                    }
                }


                //找到一个，进行消除和合并
                foreach (var findIndex in findItems)
                {
                    int itemRow = findIndex / GameStatics.RowColumnCount;
                    int itemColumn = findIndex % GameStatics.RowColumnCount;

                    changeInfoList.Add(new LocationChangeInfo()
                    {
                        FromColumn = itemColumn,
                        FromRow = itemRow,
                        ToColumn = aimColumn,
                        ToRow = aimRow
                    });
                    if (moguItems[itemRow, itemColumn] != null)
                    {
                        moguItems[itemRow, itemColumn].Hide();
                    }
                }

                bool isCanContinueElimination = MoguLogicHelper.IsCanContinueHebin(type, moguLevel);

                delay = 300;
                if (isCanContinueElimination)
                {
                    delay = ExchangeItem(changeInfoList);
                }

                //音效
                if (type == MoguType.BlueMogu)
                {
                    SoundManager.PlayEffect(SoundManager.ele_diamond);
                }
                else if (type == MoguType.ET)
                {
                    SoundManager.PlayEffect(SoundManager.ele_et);
                }
                else if (type == MoguType.OrangeMogu)
                {
                    SoundManager.PlayEffect(SoundManager.ele_wood);
                }
                else if (type == MoguType.NewLife)
                {
                    SoundManager.PlayEffect(SoundManager.ele_life);
                }

                DispatcherTimer afterEliminateTimer = new DispatcherTimer();
                afterEliminateTimer.Interval = TimeSpan.FromMilliseconds(delay);
                afterEliminateTimer.Tick += (object sender, EventArgs e) =>
                {
                    //停止Timer
                    afterEliminateTimer.Stop();

                    //分数计算逻辑Here
                    currentCombo++;

                    if (type != MoguType.NewLife)
                    {
                        //增加分数
                        int addScore = MoguDataHelper.GetScore(moguLevel, findItems.Count, currentCombo);
                        int addExtreLife = MoguDataHelper.GetNewLife(findItems.Count, currentCombo);
                        GamePage.Instance.AddScore(addScore, addExtreLife, currentCombo);
                    }
                    else
                    {
                        //增加生命
                        int addExtreLife = MoguDataHelper.GetNewLifeEliminate(findItems.Count, currentCombo);
                        if (addExtreLife > 0)
                        {
                            GamePage.Instance.AddScore(0, addExtreLife, currentCombo);
                        }
                    }

                    //待紧缩的列
                    List<int> columns = new List<int>();

                    foreach (var item in changeInfoList)
                    {
                        if (!columns.Contains(item.FromColumn))
                        {
                            columns.Add(item.FromColumn);
                        }
                        //消除
                        if (moguItems[item.FromRow, item.FromColumn] != null)
                        {
                            this.Children.Remove(moguItems[item.FromRow, item.FromColumn]);
                            moguItems[item.FromRow, item.FromColumn] = null;
                        }
                        datas[item.FromRow, item.FromColumn].Type = MoguType.Null;
                    }

                    //新增一个合并后的项目
                    if (datas[aimRow, aimColumn].Type == MoguType.Null)
                    {
                        //判断是否继续合成
                        if (isCanContinueElimination)
                        {
                            datas[aimRow, aimColumn].Type = type;
                            datas[aimRow, aimColumn].Level = moguLevel + 1;
                            moguItems[aimRow, aimColumn] = new MoguItem();
                            moguItems[aimRow, aimColumn].SetMoguUI(datas[aimRow, aimColumn]);
                            Canvas.SetTop(moguItems[aimRow, aimColumn], aimRow * GameStatics.ItemSize);
                            Canvas.SetLeft(moguItems[aimRow, aimColumn], aimColumn * GameStatics.ItemSize);
                            moguItems[aimRow, aimColumn].grid.Opacity = 0;
                            this.Children.Add(moguItems[aimRow, aimColumn]);
                            moguItems[aimRow, aimColumn].Show();
                            lastEmptyColumn = -1;
                            lastEmptyRow = -1;
                        }
                        else
                        {
                            //TODO lc 做各种动画道具处理
                            if (type == MoguType.OrangeMogu)
                            {
                                //木头
                                AddWoodTool(aimRow, aimColumn);
                            }
                            else if (type == MoguType.ET)
                            {
                                AddBombTool(aimRow, aimColumn);
                            }
                        }
                    }

                    //消除完毕，落下item，填补新item
                    foreach (int column in columns)
                    {
                        MoveBottom(column);
                    }
                    //新增moguItem
                    AddNewMoguItem();

                    //DispatcherTimer movedownTimer = new DispatcherTimer();
                    //movedownTimer.Interval = TimeSpan.FromMilliseconds(77);
                    //movedownTimer.Tick += (object sss, EventArgs eee) =>
                    //    {
                    //        movedownTimer.Stop();
                    //        //消除完毕，落下item，填补新item
                    //        foreach (int column in columns)
                    //        {
                    //            MoveBottom(column);
                    //        }
                    //        //新增moguItem
                    //        AddNewMoguItem();
                    //    };
                    //movedownTimer.Start();



                };
                afterEliminateTimer.Start();
            }
            else
            {
                //重置Combo
                currentCombo = 0;

                //允许用户操作
                lock (isDoingJobSyncObj)
                {
                    isDoingJob = false;
                }

                //设置锁定的UI
                UpdateLockUI();

                //检查游戏是否结束
                if (GamePage.Instance.currLife <= 0)
                {
                    //TODO lc 结束游戏
                    GamePage.Instance.FinishGame();
                }
            }

        }

        private void AddNewMoguItem()
        {
            int maxColumnBlank = 0;
            int columnBlank = 0;
            //增加新的符文
            for (int j = 0; j < GameStatics.RowColumnCount; j++)
            {
                for (int i = 0; i < GameStatics.RowColumnCount; i++)
                {
                    if (i == 0)
                    {
                        columnBlank = 0;
                        //计算每一列的空缺
                        for (int k = 0; k < GameStatics.RowColumnCount; k++)
                        {
                            if (datas[k, j].Type == MoguType.Null)
                            {
                                columnBlank++;
                            }
                        }
                    }
                    if (datas[i, j].Type == MoguType.Null)
                    {
                        if (columnBlank > maxColumnBlank)
                        {
                            maxColumnBlank = columnBlank;
                        }

                        //生成数据
                        datas[i, j].Type = MoguLogicHelper.GenMoguType
                            (GamePage.Instance.currScore >= GameStatics.ETAppearScore && MoguLogicHelper.GetCurrentET1Count(datas) < 4);
                        datas[i, j].Level = MoguLogicHelper.GenLevel(datas[i, j].Type);
                        moguItems[i, j] = new MoguItem();
                        moguItems[i, j].SetMoguUI(datas[i, j]);


                        Canvas.SetTop(moguItems[i, j], i * GameStatics.ItemSize);
                        Canvas.SetLeft(moguItems[i, j], j * GameStatics.ItemSize);
                        moguItems[i, j].grid.Opacity = 0;
                        this.Children.Add(moguItems[i, j]);
                        moguItems[i, j].Show(columnBlank);
                    }
                }
            }

            DispatcherTimer otherProcessTimer = new DispatcherTimer();
            otherProcessTimer.Interval = TimeSpan.FromMilliseconds(GameStatics.baseDuration * maxColumnBlank + 150);
            otherProcessTimer.Tick += (object sender2, EventArgs ee) =>
            {
                otherProcessTimer.Stop();
                CheckEliminate();
            };
            otherProcessTimer.Start();
        }

        /// <summary>
        /// 向下移动
        /// </summary>
        /// <param name="column"></param>
        /// <returns></returns>
        private double MoveBottom(int column)
        {
            double result = 0;
            List<LocationChangeInfo> needToExchange = new List<LocationChangeInfo>();

            // 找到一个空的，往后寻找，找到替换，没找到break
            for (int i = GameStatics.RowColumnCount - 1; i >= 0; i--)
            {
                MoguData data = datas[i, column];
                if (data.Type == MoguType.Null)
                {
                    LocationChangeInfo findInfo = new LocationChangeInfo();

                    for (int ii = i - 1; ii >= 0; ii--)
                    {
                        MoguData tempData = datas[ii, column];
                        if (tempData.Type != MoguType.Null)
                        {
                            if (tempData.Type == MoguType.Empty)
                            {
                                emptyRow = i;
                                emptyColumn = column;
                            }
                            findInfo.ToRow = i;
                            findInfo.ToColumn = column;
                            findInfo.FromRow = ii;
                            findInfo.FromColumn = column;
                            break;
                        }
                    }
                    if (findInfo.FromRow != -1 && findInfo.ToRow != -1)
                    {
                        //更新datas
                        MoguData temp = datas[findInfo.FromRow, findInfo.FromColumn];
                        datas[findInfo.FromRow, findInfo.FromColumn] = datas[findInfo.ToRow, findInfo.ToColumn];
                        datas[findInfo.ToRow, findInfo.ToColumn] = temp;
                        needToExchange.Add(findInfo);
                    }
                    else
                    {
                        break;
                    }
                }
            }
            // 互换并更新界面
            result = ExchangeItem(needToExchange);

            foreach (var findInfo in needToExchange)
            {
                //更新runes
                MoguItem temp = moguItems[findInfo.FromRow, findInfo.FromColumn];
                moguItems[findInfo.FromRow, findInfo.FromColumn] = moguItems[findInfo.ToRow, findInfo.ToColumn];
                moguItems[findInfo.ToRow, findInfo.ToColumn] = temp;
            }

            return result;
        }


        /// <summary>
        /// 交换
        /// </summary>
        /// <param name="needToExchange"></param>
        /// <param name="isOp"></param>
        /// <returns>返回动画结束的毫秒信息</returns>
        private double ExchangeItem(List<LocationChangeInfo> needToExchange)
        {
            double maxDuration = 0;
            foreach (var item in needToExchange)
            {
                //做动画改变位置
                MoguItem rune = moguItems[item.FromRow, item.FromColumn];
                if (rune != null)
                {
                    Storyboard storyBoard = new Storyboard();
                    double durations = GetDuration(item);
                    Duration duration = new Duration(TimeSpan.FromMilliseconds(durations));

                    if (durations > maxDuration)
                    {
                        maxDuration = durations;
                    }

                    DoubleAnimation daX = new DoubleAnimation();
                    daX.Duration = duration;
                    daX.To = item.ToColumn * GameStatics.ItemSize;
                    DoubleAnimation daY = new DoubleAnimation();
                    daY.Duration = duration;
                    daY.To = item.ToRow * GameStatics.ItemSize;

                    //弹跳
                    QuadraticEase bounce = new QuadraticEase();
                    bounce.EasingMode = EasingMode.EaseIn;
                    //bounce.Bounces = 2;
                    //bounce.Bounciness = 5;
                    daX.EasingFunction = bounce;
                    daY.EasingFunction = bounce;

                    Storyboard.SetTarget(storyBoard, rune);
                    Storyboard.SetTargetProperty(daX, new PropertyPath(Canvas.LeftProperty));
                    Storyboard.SetTargetProperty(daY, new PropertyPath(Canvas.TopProperty));
                    storyBoard.Children.Add(daX);
                    storyBoard.Children.Add(daY);

                    storyBoard.Begin();
                }
            }

            return maxDuration;
        }

        private double GetDuration(LocationChangeInfo item)
        {
            //根据移动的位置计算
            if (Math.Abs(item.FromRow - item.ToRow) > Math.Abs(item.FromColumn - item.ToColumn))
            {
                return GameStatics.baseDuration * Math.Abs(item.FromRow - item.ToRow);
            }
            else
            {
                return GameStatics.baseDuration * Math.Abs(item.FromColumn - item.ToColumn);
            }
        }

        #region 移动逻辑

        private bool MoveLeft(int selectRow, int selectColumn)
        {
            if (selectRow == emptyRow)
            {
                if (selectColumn > emptyColumn)
                {
                    if (MoguLogicHelper.CanMove(datas, 0, selectRow, selectColumn, emptyRow, emptyColumn))
                    {
                        //音效
                        SoundManager.PlayEffect(SoundManager.move);
                        lastEmptyRow = emptyRow;
                        lastEmptyColumn = emptyColumn;
                        List<LocationChangeInfo> changeInfoList = new List<LocationChangeInfo>();
                        //do it
                        for (int i = emptyColumn; i <= selectColumn - 1; i++)
                        {
                            //找到交换位置，数据交换
                            LocationChangeInfo lcInfo = new LocationChangeInfo();
                            lcInfo.FromRow = selectRow;
                            lcInfo.FromColumn = i + 1;
                            lcInfo.ToRow = selectRow;
                            lcInfo.ToColumn = i;
                            changeInfoList.Add(lcInfo);
                        }

                        ExchangeData(changeInfoList);

                        emptyRow = selectRow;
                        emptyColumn = selectColumn;

                        return true;
                    }
                    else
                    {
                        //TODO lc 提示用户被锁定
                        return false;
                    }
                }
            }
            return false;
        }

        private bool MoveTop(int selectRow, int selectColumn)
        {
            if (selectColumn == emptyColumn)
            {
                if (selectRow > emptyRow)
                {
                    if (MoguLogicHelper.CanMove(datas, 2, selectRow, selectColumn, emptyRow, emptyColumn))
                    {
                        //音效
                        SoundManager.PlayEffect(SoundManager.move);
                        lastEmptyRow = emptyRow;
                        lastEmptyColumn = emptyColumn;
                        List<LocationChangeInfo> changeInfoList = new List<LocationChangeInfo>();
                        //do it
                        for (int i = emptyRow; i <= selectRow - 1; i++)
                        {
                            //找到交换位置，数据交换
                            LocationChangeInfo lcInfo = new LocationChangeInfo();
                            lcInfo.FromRow = i + 1;
                            lcInfo.FromColumn = selectColumn;
                            lcInfo.ToRow = i;
                            lcInfo.ToColumn = selectColumn;
                            changeInfoList.Add(lcInfo);
                        }

                        ExchangeData(changeInfoList);

                        emptyRow = selectRow;
                        emptyColumn = selectColumn;

                        return true;
                    }
                    else
                    {
                        //TODO lc 提示被锁定
                        return false;
                    }
                }
            }
            return false;
        }

        private bool MoveBottom(int selectRow, int selectColumn)
        {
            if (selectColumn == emptyColumn)
            {
                if (selectRow < emptyRow)
                {
                    if (MoguLogicHelper.CanMove(datas, 3, selectRow, selectColumn, emptyRow, emptyColumn))
                    {
                        //音效
                        SoundManager.PlayEffect(SoundManager.move);
                        lastEmptyRow = emptyRow;
                        lastEmptyColumn = emptyColumn;
                        List<LocationChangeInfo> changeInfoList = new List<LocationChangeInfo>();
                        //do it
                        for (int i = emptyRow - 1; i >= selectRow; i--)
                        {
                            //找到交换位置，数据交换
                            LocationChangeInfo lcInfo = new LocationChangeInfo();
                            lcInfo.FromRow = i;
                            lcInfo.FromColumn = selectColumn;
                            lcInfo.ToRow = i + 1;
                            lcInfo.ToColumn = selectColumn;
                            changeInfoList.Add(lcInfo);
                        }

                        ExchangeData(changeInfoList);

                        emptyRow = selectRow;
                        emptyColumn = selectColumn;

                        return true;
                    }
                    else
                    {
                        //TODO lc 提示用户被锁定
                        return false;
                    }
                }
            }
            return false;
        }

        private bool MoveRight(int selectRow, int selectColumn)
        {
            if (selectRow == emptyRow)
            {
                if (selectColumn < emptyColumn)
                {
                    if (MoguLogicHelper.CanMove(datas, 1, selectRow, selectColumn, emptyRow, emptyColumn))
                    {
                        //音效
                        SoundManager.PlayEffect(SoundManager.move);
                        lastEmptyRow = emptyRow;
                        lastEmptyColumn = emptyColumn;
                        List<LocationChangeInfo> changeInfoList = new List<LocationChangeInfo>();
                        //do it
                        for (int i = emptyColumn - 1; i >= selectColumn; i--)
                        {
                            //找到交换位置，数据交换
                            LocationChangeInfo lcInfo = new LocationChangeInfo();
                            lcInfo.FromRow = selectRow;
                            lcInfo.FromColumn = i;
                            lcInfo.ToRow = selectRow;
                            lcInfo.ToColumn = i + 1;
                            changeInfoList.Add(lcInfo);
                        }

                        ExchangeData(changeInfoList);

                        emptyRow = selectRow;
                        emptyColumn = selectColumn;

                        return true;
                    }
                    else
                    {
                        //TODO lc 提示用户被锁定
                        return false;
                    }
                }
            }
            return false;
        }

        #endregion

        /// <summary>
        /// 获取滑动方向(滑动过程中)
        /// </summary>
        /// <param name="point"></param>
        /// <returns></returns>
        private int GetDirectionInMoving(Point point)
        {
            int result = -1;
            if (Math.Abs(point.X) > Math.Abs(point.Y))
            {
                //左右
                if (point.X > 0)
                {
                    //向右
                    result = 1;
                }
                else
                {
                    result = 0;
                }
            }
            else
            {
                //上下
                if (point.Y > 0)
                {
                    //top
                    result = 3;
                }
                else
                {
                    //down
                    result = 2;
                }
            }


            return result;
        }

        /// <summary>
        /// 获取滑动方向
        /// </summary>
        /// <param name="point"></param>
        /// <returns></returns>
        private int GetDirection(Point point)
        {
            int result = -1;

            if (Math.Abs(point.Y) < Math.Abs(point.X))
            {
                if (point.X < -40 && Math.Abs(point.Y) < 80)
                {
                    //向左
                    result = 0;
                }
                else if (point.X > 40 && Math.Abs(point.Y) < 80)
                {
                    //向右
                    result = 1;
                }
            }
            else
            {
                if (Math.Abs(point.X) < 80 && point.Y < -40)
                {
                    //向上
                    result = 2;
                }
                else if (Math.Abs(point.X) < 80 && point.Y > 40)
                {
                    //向下
                    result = 3;
                }
            }

            //第二轮筛选
            if (result == -1)
            {
                if (point.X < -40 && Math.Abs(point.Y) < 80)
                {
                    //向左
                    result = 0;
                }
                else if (point.X > 40 && Math.Abs(point.Y) < 80)
                {
                    //向右
                    result = 1;
                }
                else if (Math.Abs(point.X) < 80 && point.Y < -40)
                {
                    //向上
                    result = 2;
                }
                else if (Math.Abs(point.X) < 80 && point.Y > 40)
                {
                    //向下
                    result = 3;
                }
            }

            return result;
        }

        /// <summary>
        /// 递归寻找逻辑
        /// </summary>
        /// <param name="itemType"></param>
        /// <param name="row"></param>
        /// <param name="column"></param>
        /// <param name="findType"></param>
        /// <param name="items"></param>
        private void FindRelationGameItem(MoguType itemType, int level, int row, int column, FindType findType, List<int> items)
        {
            if (findType != FindType.Bottom)
            {
                //向上找
                if (row - 1 >= 0)
                {
                    if (datas[row - 1, column].Type == itemType && datas[row - 1, column].Level == level)
                    {
                        int itemKey = (row - 1) * GameStatics.RowColumnCount + column;
                        if (!items.Contains(itemKey))
                        {
                            items.Add(itemKey);
                            //继续找
                            FindRelationGameItem(itemType, level, row - 1, column, FindType.Top, items);
                        }
                    }
                }
            }
            if (findType != FindType.Top)
            {
                //向下找
                if (row + 1 < GameStatics.RowColumnCount)
                {
                    if (datas[row + 1, column].Type == itemType && datas[row + 1, column].Level == level)
                    {
                        int itemKey = (row + 1) * GameStatics.RowColumnCount + column;
                        if (!items.Contains(itemKey))
                        {
                            items.Add(itemKey);
                            //继续找
                            FindRelationGameItem(itemType, level, row + 1, column, FindType.Bottom, items);
                        }
                    }
                }
            }
            if (findType != FindType.Right)
            {
                //向左找
                if (column - 1 >= 0)
                {
                    if (datas[row, column - 1].Type == itemType && datas[row, column - 1].Level == level)
                    {
                        int itemKey = row * GameStatics.RowColumnCount + column - 1;
                        if (!items.Contains(itemKey))
                        {
                            items.Add(itemKey);
                            //继续找
                            FindRelationGameItem(itemType, level, row, column - 1, FindType.Left, items);
                        }
                    }
                }
            }

            if (findType != FindType.Left)
            {
                //向右找
                if (column + 1 < GameStatics.RowColumnCount)
                {
                    if (datas[row, column + 1].Type == itemType && datas[row, column + 1].Level == level)
                    {
                        int itemKey = row * GameStatics.RowColumnCount + column + 1;
                        if (!items.Contains(itemKey))
                        {
                            items.Add(itemKey);
                            //继续找
                            FindRelationGameItem(itemType, level, row, column + 1, FindType.Right, items);
                        }
                    }
                }
            }
        }

        internal Dictionary<int, MoguData> GetGameData()
        {
            return MoguDataHelper.MoguDataToDictionary(datas);
        }

        internal void Rearrange()
        {
            if (MessageBox.Show("Use STORM need " + GameStatics.ToolPriceRearrange + " Gold，Determine to use ?", "Use tool", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                if (StageManager.Instance.TotalG >= GameStatics.ToolPriceRearrange)
                {
                    StageManager.Instance.TotalG -= GameStatics.ToolPriceRearrange;

                    //音效
                    SoundManager.PlayEffect(SoundManager.rearrange);

                    lock (isDoingJobSyncObj)
                    {
                        if (isDoingJob)
                        {
                            isManipulationStarted = false;
                            return;
                        }
                        isDoingJob = true;
                    }

                    List<LocationChangeInfo> changeInfo = new List<LocationChangeInfo>();
                    List<LocationChangeInfo> changeInfoRevert = new List<LocationChangeInfo>();
                    List<int> useageLeftIndex = new List<int>();
                    for (int i = 0; i < GameStatics.RowColumnCount / 2; i++)
                    {
                        for (int j = 0; j < GameStatics.RowColumnCount; j++)
                        {
                            if (i != emptyRow || j != emptyColumn)
                            {
                                //进行交换
                                int aimRow = r.Next(GameStatics.RowColumnCount / 2) + GameStatics.RowColumnCount / 2;
                                int aimColumn = r.Next(GameStatics.RowColumnCount);

                                int index = GetIndex(aimRow, aimColumn);
                                while (useageLeftIndex.Contains(index))
                                {
                                    aimRow = r.Next(GameStatics.RowColumnCount / 2) + GameStatics.RowColumnCount / 2;
                                    aimColumn = r.Next(GameStatics.RowColumnCount);

                                    index = GetIndex(aimRow, aimColumn);
                                }

                                if (aimRow == emptyRow && aimColumn == emptyColumn)
                                {
                                    continue;
                                }

                                useageLeftIndex.Add(index);

                                changeInfo.Add(new LocationChangeInfo()
                                {
                                    FromColumn = j,
                                    FromRow = i,
                                    ToColumn = aimColumn,
                                    ToRow = aimRow
                                });


                                changeInfoRevert.Add(new LocationChangeInfo()
                                {
                                    ToColumn = j,
                                    ToRow = i,
                                    FromColumn = aimColumn,
                                    FromRow = aimRow
                                });
                            }
                        }
                    }

                    ExchangeItem(changeInfoRevert);
                    ExchangeData(changeInfo);
                    //设置锁定的UI
                    UpdateLockUI();
                }
                else
                {
                    //提示金币不足
                    MessageBox.Show("Sorry, you have not enough gold.");
                }
            }
        }

        List<List<int>> woodToolItems = new List<List<int>>();

        internal void UseWood()
        {
            if (this.ToolUseStatus == 0)
            {
                List<int> findedIndex = new List<int>();
                List<int> findList = new List<int>();

                woodToolItems.Clear();

                //寻找所有两个在一起的项
                for (int i = 0; i < GameStatics.RowColumnCount; i++)
                {
                    for (int j = 0; j < GameStatics.RowColumnCount; j++)
                    {
                        //开始寻找
                        if (datas[i, j].Type != MoguType.NewLife)
                        {
                            findList.Clear();
                            findList.Add(GetIndex(i, j));
                            FindRelationGameItem(datas[i, j].Type, datas[i, j].Level, i, j, FindType.All, findList);
                            if (findList.Count >= 2)
                            {
                                if (findList.Count == 2)
                                {
                                    //是需要使用道具的东西
                                    bool isLegelData = true;
                                    List<int> indexLst = new List<int>();
                                    foreach (var index in findList)
                                    {
                                        if (!findedIndex.Contains(index))
                                        {
                                            indexLst.Add(index);
                                        }
                                        else
                                        {
                                            isLegelData = false;
                                            break;
                                        }
                                    }
                                    if (isLegelData)
                                    {
                                        woodToolItems.Add(indexLst);
                                    }
                                }
                                //进行记录
                                foreach (var index in findList)
                                {
                                    if (!findedIndex.Contains(index))
                                    {
                                        findedIndex.Add(index);
                                    }
                                }
                            }
                        }
                    }
                }

                if (woodToolItems.Count > 0)
                {
                    this.ToolUseStatus = 1;
                    //有结果，在界面中进行显示
                    foreach (var lst in woodToolItems)
                    {
                        foreach (var index in lst)
                        {
                            int sRow = index / GameStatics.RowColumnCount;
                            int sColumn = index % GameStatics.RowColumnCount;

                            moguItems[sRow, sColumn].SetWoodStatus();
                        }
                    }
                }
                else
                {
                    //TODO lc 没有发现两个的项目
                    MessageBox.Show("Can't find items can use wood.");
                }

            }
            else
            {
                woodToolItems.Clear();
                CancelToolStatus();
            }
        }

        private int GetIndex(int i, int j)
        {
            return i * GameStatics.RowColumnCount + j;
        }

        internal void UseBomb()
        {
            if (this.ToolUseStatus == 0)
            {
                //所有的MoguItem都需要设置成道具使用模式
                this.ToolUseStatus = 2;

                for (int i = 0; i < GameStatics.RowColumnCount; i++)
                {
                    for (int j = 0; j < GameStatics.RowColumnCount; j++)
                    {
                        if (moguItems[i, j] != null)
                        {
                            moguItems[i, j].SetBombStatus();
                        }
                    }
                }
            }
            else
            {
                CancelToolStatus();
            }
        }

        private void CancelToolStatus()
        {
            this.ToolUseStatus = 0;
            for (int i = 0; i < GameStatics.RowColumnCount; i++)
            {
                for (int j = 0; j < GameStatics.RowColumnCount; j++)
                {
                    if (moguItems[i, j] != null)
                    {
                        moguItems[i, j].CancelToolStatus();
                    }
                }
            }
        }

        private void AddWoodTool(int r, int c)
        {
            StageManager.Instance.WoodCount++;

            toolItem.SetToWood();
            toolItem.Show();
            //动画
            CompositeTransform trans = this.toolItem.RenderTransform as CompositeTransform;
            Duration duration = new Duration(TimeSpan.FromMilliseconds(1000));
            //动画
            DoubleAnimation xAnimation = new DoubleAnimation
            {
                From = c * GameStatics.ItemSize + GameStatics.ItemSize / 2 - 240,
                To = 0,
                Duration = duration,
                //EasingFunction = new QuinticEase()
            };
            DoubleAnimation yAnimation = new DoubleAnimation
            {
                From = r * GameStatics.ItemSize + GameStatics.ItemSize / 2 - 240,
                To = 290,
                Duration = duration,
                //EasingFunction = new QuinticEase()
            };
            Storyboard.SetTargetProperty(xAnimation, new PropertyPath("TranslateX"));
            Storyboard.SetTargetProperty(yAnimation, new PropertyPath("TranslateY"));

            Storyboard storyboard = new Storyboard { };
            Storyboard.SetTarget(storyboard, toolItem.RenderTransform);
            storyboard.Children.Add(xAnimation);
            storyboard.Children.Add(yAnimation);
            //storyboard.BeginTime = TimeSpan.FromMilliseconds(600);
            storyboard.Begin();

            GamePage.Instance.UpdateStatusUI();
        }


        private void AddBombTool(int r, int c)
        {
            StageManager.Instance.BombCount++;

            toolItem.SetToBomb();
            toolItem.Show();
            //动画
            CompositeTransform trans = this.toolItem.RenderTransform as CompositeTransform;
            Duration duration = new Duration(TimeSpan.FromMilliseconds(1000));
            //动画
            DoubleAnimation xAnimation = new DoubleAnimation
            {
                From = c * GameStatics.ItemSize + GameStatics.ItemSize / 2 - 240,
                To = 157,
                Duration = duration,
                EasingFunction = new QuinticEase()
            };
            DoubleAnimation yAnimation = new DoubleAnimation
            {
                From = r * GameStatics.ItemSize + GameStatics.ItemSize / 2 - 240,
                To = 290,
                Duration = duration,
                EasingFunction = new QuinticEase()
            };
            Storyboard.SetTargetProperty(xAnimation, new PropertyPath("TranslateX"));
            Storyboard.SetTargetProperty(yAnimation, new PropertyPath("TranslateY"));

            Storyboard storyboard = new Storyboard { };
            Storyboard.SetTarget(storyboard, toolItem.RenderTransform);
            storyboard.Children.Add(xAnimation);
            storyboard.Children.Add(yAnimation);
            //storyboard.BeginTime = TimeSpan.FromMilliseconds(600);
            storyboard.Begin();

            GamePage.Instance.UpdateStatusUI();
        }

        internal void Pause()
        {

        }
    }
}
